import React from 'react';

import { createFromIconfontCN } from '@ant-design/icons';
import clsx from 'clsx';

/**
 * 自定义 IconFont 图标组件
 * 使用方法：<IconFont type="icon-xxx"  style className/>
 */

export const IconFont = createFromIconfontCN({
  scriptUrl: import.meta.env.VITE_ICONFONT_URL,
});
// 图标缓存
const iconCache: Record<string, React.FC<React.SVGProps<SVGSVGElement>>> = {};

// 动态加载图标
const loadIcon = async (name: string): Promise<React.FC<React.SVGProps<SVGSVGElement>> | null> => {
  if (iconCache[name]) {
    return iconCache[name];
  }

  try {
    const module = await import(`@/assets/icon/${name}.svg?react`);
    const IconComponent = module.default;
    iconCache[name] = IconComponent;
    return IconComponent;
  } catch (error) {
    console.warn(`Failed to load icon: ${name}`, error);
    return null;
  }
};

type SvgIconProps = {
  name: string; // 图标名（不含后缀）
  className?: string; // 自定义类名
  strokeColor?: string; // 自定义描边颜色
  fillColor?: string; // 自定义填充颜色
  style?: React.CSSProperties; // 外部传入样式
  onClick?: () => void; // 点击事件
};

const SvgIcon: React.FC<SvgIconProps> = ({
  name,
  className = '',
  strokeColor,
  fillColor,
  style = {},
  onClick,
}) => {
  const [Component, setComponent] = React.useState<React.FC<React.SVGProps<SVGSVGElement>> | null>(
    null
  );
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    const loadIconComponent = async () => {
      setLoading(true);
      // console.log(`Loading icon: ${name}`); // 调试信息
      const IconComponent = await loadIcon(name);
      // console.log(`Icon loaded: ${name}`, IconComponent ? 'success' : 'failed'); // 调试信息
      setComponent(() => IconComponent);
      setLoading(false);
    };

    loadIconComponent();
  }, [name]);

  if (loading) {
    return (
      <div
        style={{
          width: '1em',
          height: '1em',
          backgroundColor: '#f0f0f0',
          display: 'inline-block',
          borderRadius: '2px',
          ...style,
        }}
        className={className}
      />
    );
  }

  if (!Component) {
    console.warn(`SVG icon "${name}" not found, falling back to IconFont`);
    // 回退到 IconFont
    return <IconFont type={name} className={className} style={style} />;
  }

  return (
    <Component
      width="1em"
      height="1em"
      className={clsx(className)}
      style={{
        // stroke: strokeColor || 'currentColor',
        fill: fillColor || 'currentColor',
        display: 'inline-block',
        verticalAlign: 'middle',
        cursor: onClick ? 'pointer' : 'default',
        ...style,
      }}
      onClick={onClick}
    />
  );
};

export default SvgIcon;
